<template>
    <div>
        <el-form label-width="80px" :model="skuInfoFrom" :rules="rules" ref="ruleFormRef" status-icon>
            <el-form-item label="SKU名称" prop="skuName">
                <el-input placeholder="请输入SKU名称" style="width: 250px" v-model="skuInfoFrom.skuName" />
            </el-form-item>
            <el-form-item label="价格(元)" prop="price">
                <el-input placeholder="请输入价格(元)" style="width: 250px" type="number" v-model="skuInfoFrom.price" />
            </el-form-item>
            <el-form-item label="重量(克)" prop="weight">
                <el-input placeholder="重量(克)" style="width: 250px" type="number" v-model="skuInfoFrom.weight" />
            </el-form-item>
            <el-form-item label="SKU描述" prop="skuDesc">
                <el-input placeholder="请输入SKU描述" type="textarea" :rows="5" style="width: 70%"
                    v-model="skuInfoFrom.skuDesc" />
            </el-form-item>
            <el-form-item label="平台属性" style="width: 70%" prop="skuAttrValueList">
                <el-form inline label-width="85px">
                    <div class="flex-container">
                        <el-form-item v-for="(item) in attrInfoList" :label="item.attrName" :key="(item.id as number)">
                            <el-select placeholder="请选择" style="width: 150px" v-model="item.selectedAttrValueId"
                                @change="changeSkuAttrValue">
                                <el-option v-for="(attrValue) in item.attrValueList" :key="(attrValue.id as number)"
                                    :label="attrValue.valueName" :value="(attrValue.id as number)" />
                            </el-select>
                        </el-form-item>
                    </div>
                </el-form>
            </el-form-item>
            <el-form-item label="销售属性" style="width: 70%" prop="skuSaleAttrValueList">
                <el-form inline label-width="85px">
                    <div class="flex-container">
                        <el-form-item v-for="(item) in spuSaleAttrList" :label="item.saleAttrName"
                            :key="(item.id as number)">
                            <el-select placeholder="请选择" style="width: 150px" v-model="item.selectedSpuSaleAttrValueId"
                                @change="changeskuSaleAttrValue">
                                <el-option v-for="(attrValue) in item.spuSaleAttrValueList"
                                    :key="(attrValue.id as number)" :label="attrValue.saleAttrValueName"
                                    :value="(attrValue.id as number)" />
                            </el-select>
                        </el-form-item>
                    </div>
                </el-form>
            </el-form-item>
            <el-form-item label="图片名称" prop="skuDefaultImg">
                <el-table border style="width: 70%" :data="spuImageList" ref="skuImgTable">
                    <el-table-column align="center" type="selection" width="80" />
                    <el-table-column align="center" label="图片">
                        <template #default="{ row }">
                            <el-image :src="row.imgUrl" width="10px">
                                <template #placeholder>
                                    <div class="image-slot">Loading<span class="dot">...</span></div>
                                </template>
                            </el-image>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="图片名称" prop="imgName" />
                    <el-table-column align="center" label="操作" width="150">
                        <template #default="{ row }">
                            <el-button type="primary" @click="setDefaultImg(row)">设置默认图片</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitSkuInfo(ruleFormRef)" :loading="butLoading">提交</el-button>
                <el-button type="danger" @click="close">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang='ts'>
import type { AttrInfo } from '@/api/product/attr/type';
import spuConstant from './spuConstant';
import { getAttrInfoList } from '@/api/product/attr';
import { reqSaveSkuInfo, reqSpuImageList, reqSpuSaleAttrList } from '@/api/product/spu';
import type { SpuImageType, SpuSaleAttrType, SkuType } from '@/api/product/spu/type';
import type { ResponseData } from '@/api/type';
import type { ElTable, FormInstance, FormRules } from 'element-plus';

let spuImageList = ref<SpuImageType[]>();
let attrInfoList = ref<AttrInfo[]>([]);
let spuSaleAttrList = ref<SpuSaleAttrType[]>([]);
let oldCategory3Id = ref<Number>();
let skuImgTable = ref<InstanceType<typeof ElTable>>();
let ruleFormRef = ref<FormInstance>();
let butLoading = ref(false);


const emit = defineEmits(['updateSpuScene']);
const { formInline } = defineProps(['formInline'])

let skuInfoFrom: SkuType = reactive({
    category3Id: formInline.category3,
    isSale: undefined,
    price: undefined,
    spuId: undefined,
    tmId: undefined,
    skuDefaultImg: '',
    skuDesc: '',
    skuName: '',
    weight: '',
    skuAttrValueList: [],
    skuImageList: [],
    skuSaleAttrValueList: []
})

const close = () => {
    ruleFormRef.value?.resetFields()
    Object.assign(skuInfoFrom, {
        isSale: undefined,
        price: undefined,
        spuId: undefined,
        tmId: undefined,
        skuDefaultImg: '',
        skuDesc: '',
        skuName: '',
        weight: '',
        skuAttrValueList: [],
        skuImageList: [],
        skuSaleAttrValueList: []
    })
    emit('updateSpuScene', spuConstant.scene_zero);
    attrInfoList.value?.forEach(item => {
        item.selectedAttrValueId = undefined
    })
    spuSaleAttrList.value?.forEach(item => {
        item.selectedSpuSaleAttrValueId = undefined
    })
}

const submitSkuInfo = (ruleForm: FormInstance | undefined) => {
    if (!ruleForm) return
    ruleForm.validate().then(() => {
        butLoading.value = true;
        // 处理平台属性
        skuInfoFrom.skuAttrValueList = attrInfoList.value?.filter(item => item.selectedAttrValueId !== undefined).map(item => {
            return {
                attrId: item.id as number,
                valueId: item.selectedAttrValueId as number
            }
        })
        // 处理销售属性
        skuInfoFrom.skuSaleAttrValueList = spuSaleAttrList.value?.filter(item => item.selectedSpuSaleAttrValueId !== undefined).map(item => {
            return {
                saleAttrId: item.id as number,
                saleAttrValueId: item.selectedSpuSaleAttrValueId as number
            }
        })
        reqSaveSkuInfo(skuInfoFrom).then(() => {
            ElMessage.success('提交成功。')
            close()
        }).catch((error: ResponseData<String>) => {
            ElMessage.error(('提交失败。') + error.message);
        })
    }).catch(() => {
        ElMessage.error('请检查输入项是否正确。')
    }).finally(() => {
        butLoading.value = false;
    })
};

const setDefaultImg = (row: SpuImageType) => {
    skuInfoFrom.skuDefaultImg = row.imgUrl
    ElMessage.success('设置默认图片成功。')
    skuImgTable.value?.clearSelection()
    skuImgTable.value?.toggleRowSelection(row)
}

const validatorSkuAttrValueList = (_rule: any, _value: any, callback: any) => {
    if (attrInfoList.value?.some(item => item.selectedAttrValueId !== undefined)) {
        callback();
        return;
    }
    callback(new Error('平台属性不能为空。'))
}

const validatorSkuSaleAttrValueList = (_rule: any, _value: any, callback: any) => {
    if (spuSaleAttrList.value?.some(item => item.selectedSpuSaleAttrValueId !== undefined)) {
        callback();
        return;
    }
    callback(new Error('销售属性不能为空。'))
}

const rules = ref<FormRules<SkuType>>({
    skuName: [{ required: true, message: 'SKU名称不能空', trigger: 'change' }],
    price: [{ required: true, message: '价格不能为空', trigger: 'change' }],
    weight: [{ required: true, message: '重量不能空', trigger: 'change' }],
    skuDesc: [{ required: true, message: 'SKU描述不能空', trigger: 'change' }],
    skuAttrValueList: [{ required: true, validator: validatorSkuAttrValueList }],
    skuSaleAttrValueList: [{ required: true, validator: validatorSkuSaleAttrValueList }],
    skuDefaultImg: [{ required: true, message: '需要选择一个默认图片。', trigger: 'change' }]
});


const changeSkuAttrValue = () => {
    ruleFormRef.value?.clearValidate('skuAttrValueList')
}

const changeskuSaleAttrValue = () => {
    ruleFormRef.value?.clearValidate('skuSaleAttrValueList')
}

const getData = (spuId: number, tmId: number) => {
    skuInfoFrom.spuId = spuId
    skuInfoFrom.tmId = tmId
    skuInfoFrom.category3Id = formInline.category3
    spuImageList.value = []
    spuSaleAttrList.value = []
    // 查询出SPU照片
    reqSpuImageList(spuId).then(res => {
        spuImageList.value = res.data

    }).catch((error: ResponseData<String>) => {
        ElMessage.error(('获取SPU照片失败。') + error.message);
    })

    // 查询出SPU属性
    reqSpuSaleAttrList(spuId).then(res => {
        spuSaleAttrList.value = res.data
    }).catch((error: ResponseData<String>) => {
        ElMessage.error(('获取SPU销售属性失败。') + error.message);
    })

    // 查询出平台属性, 如果分类发生变化
    if (formInline.category3 !== oldCategory3Id.value) {
        attrInfoList.value = []
        oldCategory3Id.value = formInline.category3
        console.log(formInline.category1, formInline.category2, formInline.category3)
        getAttrInfoList(formInline.category1, formInline.category2, formInline.category3).then(res => {
            attrInfoList.value = res.data
        }).catch((error: ResponseData<String>) => {
            ElMessage.error(('获取平台属性失败。') + error.message);
        })
    }
}

// 宏函数把数据交给外部
defineExpose({ getData })
</script>

<style scoped lang="scss">
.flex-container {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;

}

.el-image {
    padding: 0 5px;
    max-width: 300px;
    min-width: 70px;
}

.image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 14px;
}

.dot {
    animation: dot 2s infinite steps(3, start);
    overflow: hidden;
}
</style>